<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';
import { message } from 'ant-design-vue';
import { PlusOutlined } from '@ant-design/icons-vue';
import { useRouterPush } from '@/hooks/common/router';
import {
  fetchApiDefinitionById,
  fetchApiDefinitions,
  deleteApiDefinition as removeApiDefinition,
  saveApiDefinition as saveApiDefinitionApi
} from '@/service/api/compute';

const { routerPushByKey } = useRouterPush();
// 响应式数据
const apiDefinitions = ref<Api.Compute.ApiDefinition[]>([]);
const loading = ref(false);
const modalVisible = ref(false);
const saving = ref(false);
const isEditing = ref(false);
const searchKeyword = ref('');

// 当前编辑的接口定义
const currentApi = ref<Api.Compute.ApiDefinition>({
  id: '',
  name: '',
  bizCode: '',
  description: '',
  enabled: true
});

// 表格列定义
const columns = [
  {
    title: '接口名称',
    dataIndex: 'name',
    key: 'name'
  },
  {
    title: '业务编码',
    dataIndex: 'bizCode',
    key: 'bizCode'
  },
  {
    title: '描述',
    dataIndex: 'description',
    key: 'description',
    ellipsis: true
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status'
  },
  {
    title: '更新时间',
    dataIndex: 'updateTime',
    key: 'updateTime'
  },
  {
    title: '操作',
    key: 'action'
  }
];

// 过滤后的接口定义列表
const filteredApiDefinitions = computed(() => {
  if (!searchKeyword.value) {
    return apiDefinitions.value;
  }

  const keyword = searchKeyword.value.toLowerCase();
  return apiDefinitions.value.filter(
    api => api.name.toLowerCase().includes(keyword) || api.bizCode.toLowerCase().includes(keyword)
  );
});

// 加载接口定义列表
const loadApiDefinitions = async () => {
  loading.value = true;
  try {
    const response = await fetchApiDefinitions();
    apiDefinitions.value = response || [];
  } catch {
    message.error('加载接口定义失败');
  } finally {
    loading.value = false;
  }
};

// 显示创建接口定义对话框
const showCreateModal = () => {
  isEditing.value = false;
  currentApi.value = {
    id: '',
    name: '',
    bizCode: '',
    description: '',
    enabled: true
  };
  modalVisible.value = true;
};

// 编辑接口定义
const editApiDefinition = async (record: any) => {
  isEditing.value = true;
  try {
    const response = await fetchApiDefinitionById(record.id);
    if (response) {
      currentApi.value = response;
      modalVisible.value = true;
    } else {
      message.error('接口定义数据为空');
    }
  } catch {
    message.error('获取接口定义详情失败');
  }
};

// 保存接口定义
const saveApiDefinition = async () => {
  // 表单验证
  if (!currentApi.value.name) {
    message.warning('请输入接口名称');
    return;
  }

  if (!currentApi.value.bizCode) {
    message.warning('请输入业务编码');
    return;
  }

  saving.value = true;
  try {
    await saveApiDefinitionApi(currentApi.value);
    message.success(`${isEditing.value ? '更新' : '创建'}接口定义成功`);
    modalVisible.value = false;
    loadApiDefinitions();
  } catch {
    message.error(`${isEditing.value ? '更新' : '创建'}接口定义失败`);
  } finally {
    saving.value = false;
  }
};

// 删除接口定义
const deleteApiDefinition = async (id: string) => {
  try {
    await removeApiDefinition(id);
    message.success('删除接口定义成功');
    loadApiDefinitions();
  } catch {
    message.error('删除接口定义失败');
  }
};

// 跳转到流程设计器
const designFlow = (record: any) => {
  routerPushByKey('compute_flow-design', { query: { apiId: record.id } });
};

// 搜索处理
const handleSearch = () => {
  // 搜索逻辑已通过计算属性实现
};

// 生命周期
onMounted(() => {
  loadApiDefinitions();
});
</script>

<template>
  <div class="api-management-container">
    <div class="page-header">
      <h2>接口管理</h2>
      <p>管理动态计算引擎的API接口定义</p>
    </div>

    <div class="content-area">
      <div class="toolbar">
        <ASpace>
          <AButton type="primary" @click="showCreateModal">
            <template #icon><PlusOutlined /></template>
            新建接口定义
          </AButton>
          <AInputSearch
            v-model:value="searchKeyword"
            placeholder="搜索接口名称或业务编码"
            class="search-input"
            @search="handleSearch"
          />
        </ASpace>
      </div>

      <ATable
        :columns="columns"
        :data-source="filteredApiDefinitions"
        :loading="loading"
        :pagination="{ pageSize: 10 }"
        row-key="id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <ATag :color="record.status === 'enabled' ? 'success' : 'default'">
              {{ record.status === 'enabled' ? '启用' : '禁用' }}
            </ATag>
          </template>

          <template v-if="column.key === 'action'">
            <ASpace>
              <AButton type="link" size="small" @click="editApiDefinition(record)">编辑</AButton>
              <AButton type="link" size="small" @click="designFlow(record)">设计流程</AButton>
              <APopconfirm
                title="确定要删除此接口定义吗？"
                ok-text="确定"
                cancel-text="取消"
                @confirm="deleteApiDefinition(record.id)"
              >
                <AButton type="link" size="small" danger>删除</AButton>
              </APopconfirm>
            </ASpace>
          </template>
        </template>
      </ATable>

      <!-- 创建/编辑接口定义对话框 -->
      <AModal
        v-model:open="modalVisible"
        :title="isEditing ? '编辑接口定义' : '新建接口定义'"
        :confirm-loading="saving"
        width="700px"
        @ok="saveApiDefinition"
      >
        <AForm :model="currentApi" layout="vertical">
          <AFormItem label="接口名称" required>
            <AInput v-model:value="currentApi.name" placeholder="请输入接口名称" />
          </AFormItem>

          <AFormItem label="业务编码" required>
            <AInput v-model:value="currentApi.bizCode" placeholder="请输入业务编码" />
          </AFormItem>

          <AFormItem label="接口描述">
            <ATextarea v-model:value="currentApi.description" placeholder="请输入接口描述" :rows="3" />
          </AFormItem>

          <AFormItem label="状态">
            <ARadioGroup v-model:value="currentApi.status">
              <ARadio value="enabled">启用</ARadio>
              <ARadio value="disabled">禁用</ARadio>
            </ARadioGroup>
          </AFormItem>
        </AForm>
      </AModal>
    </div>
  </div>
</template>

<style scoped>
.api-management-container {
  padding: 24px;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #262626;
  font-size: 24px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #8c8c8c;
  font-size: 14px;
}

/* 添加暗色模式样式 */
.dark .page-header h2 {
  color: #ffffff;
}

.dark .page-header p {
  color: #a0a0a0;
}
.content-area {
  /* background: white; */
  border-radius: 8px;
  padding: 24px;
}

.toolbar {
  margin-bottom: 16px;
  display: flex;
  justify-content: space-between;
}

.search-input {
  width: 250px;
}
</style>
